package com.vince.leetcode.simple;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 *
 */
public class _1_TwoSum {

    /**
     * 地址：https://leetcode-cn.com/problems/two-sum/
     *
     * @param nums   输入的数组
     * @param target 和
     * @return int[] 返回两个数组下标
     */
    public int[] twoSum(int[] nums, int target) {
        // map: key -> 输入的整数，value -> 数组下标
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int curNum = nums[i]; // 当前遍历整数
            int anoNum = target - curNum; // 期望的另一个整数
            if (map.get(anoNum) != null) {
                return new int[]{map.get(anoNum), i};
            }
            map.put(curNum, i); // (当前整数，下标)
        }
        return new int[]{0, 0};
    }

    public static void main(String[] args) {
        _1_TwoSum solution = new _1_TwoSum();
        System.out.println(Arrays.toString(solution.twoSum(new int[]{2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(solution.twoSum(new int[]{3,2,4}, 6)));
        System.out.println(Arrays.toString(solution.twoSum(new int[]{3,3}, 6)));
    }
}
